package com.ugrow.ugrowcommunity.activity.moments;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ugrow.ugrowcommunity.BuildConfig;
import com.ugrow.ugrowcommunity.R;
import com.ugrow.ugrowcommunity.activity.moments.adapter.MomentAdapter;
import com.ugrow.ugrowcommunity.activity.moments.commentBean.CommentBean;
import com.ugrow.ugrowcommunity.activity.moments.momentBean.ArticlesBean;
import com.ugrow.ugrowcommunity.activity.moments.momentBean.Data;
import com.ugrow.ugrowcommunity.databinding.ActivityMomentsBinding;
import com.ugrow.ugrowcommunity.util.HttpUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class MomentsActivity extends AppCompatActivity {

    private ActivityMomentsBinding binding;
    private List<Data> list = new ArrayList<>();
    private MomentAdapter adapter;
    private static final String PAGE_SIZE = "7";
    private AtomicInteger pageNow = new AtomicInteger(1);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMomentsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);
        binding.toolbarLayout.setTitle(com.ugrow.ugrowcommunity.data.Data.StudentBean.getData().get(0).getStuName());
        Glide.with(this)
                .load(com.ugrow.ugrowcommunity.data.Data.StudentBean.getData().get(0).getStuPhoto())
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .into(binding.fab);
        initStatusBar();
        adapter = new MomentAdapter(list);
        binding.recyclerview.setLayoutAnimation(AnimationUtils.loadLayoutAnimation(MomentsActivity.this, R.anim.item_anim));
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(MomentsActivity.this));
        binding.recyclerview.setAdapter(adapter);
        refreshAdapter(PAGE_SIZE, true);

        initListener();
    }

    private void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    private void initListener() {
        adapter.setOnCommendClickListener(position -> {
            List<com.ugrow.ugrowcommunity.activity.moments.commentBean.Data> data = new ArrayList<>();
            CommendMsgDialogFragment commendMsgDialogFragment = new CommendMsgDialogFragment(data, list.get(position).getAuthorId());
            commendMsgDialogFragment.show(getSupportFragmentManager(), commendMsgDialogFragment.getTag());


            HashMap<String, String> map = new HashMap<>();
//            map.put("articleId", String.valueOf(list.get(position).getAuthorId()));
            HttpUtil.httpGet(BuildConfig.MOMENT_COMMENT + "/" + list.get(position).getAuthorId(), map, new HttpUtil.CallBack() {
                @Override
                public void success(HttpUtil.Result result) {
                    Log.d("TAG", "success: " + result.content);
                    if (result.success && result.code == 200) {
                        CommentBean commentBean = new Gson().fromJson(result.content, CommentBean.class);
                        commendMsgDialogFragment.refreshList(commentBean.getData());
                    }
                }

                @Override
                public void failed(IOException e) {
                    Toast.makeText(MomentsActivity.this, "请求失败！", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            });

        });

        binding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            //下拉刷新
            Log.d("TAG", "initListener: 正在刷新");
            refreshAdapter(PAGE_SIZE, true);
            refreshLayout.finishRefresh();
        });
        binding.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            //上拉加载
            Log.d("TAG", "initListener: 正在加载");
            refreshAdapter(PAGE_SIZE, false);
            refreshLayout.finishLoadMore();
        });

        binding.appBar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                //折叠
                binding.refreshLayout.setBackgroundResource(R.color.colorPrimary);
            } else {
                //中间状态
                binding.refreshLayout.setBackgroundColor(Color.parseColor("#444444"));
            }
        });

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }


    private void refreshAdapter(String pageSize, boolean refreshAll) {
        HashMap<String, String> map = new HashMap<>();
        map.put("pageNow", String.valueOf(pageNow.getAndIncrement()));
        map.put("pageSize", pageSize);
        HttpUtil.httpGet(BuildConfig.MOMENT_ARTICLES, map, new HttpUtil.CallBack() {
            @Override
            public void success(HttpUtil.Result result) {
                Log.d("TAG", "success: " + result.content);
                if (result.code == 200) {
                    try {
                        ArticlesBean articlesBean = new Gson().fromJson(result.content, ArticlesBean.class);
                        if (articlesBean.getResult()) {
                            if (refreshAll) {
                                list = articlesBean.getData();
                            } else {
                                list.addAll(articlesBean.getData());
                            }
                            adapter.dispatchUpdate(list);
                            Log.d("TAG", "success: " + list.size());
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                        Toast.makeText(MomentsActivity.this, "没有更多啦~", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void failed(IOException e) {
                e.printStackTrace();
            }
        });
    }
}